<template>
  <div class="assign-task">
    <div class="page-header">
      <div class="header-left">
        <el-button @click="goBack" type="text" class="back-btn">
          <el-icon><ArrowLeft /></el-icon>
          返回
        </el-button>
        <div class="header-content">
          <h1>分配任务</h1>
          <p>为任务分配负责人和设置相关参数</p>
        </div>
      </div>
    </div>

    <div class="content-container">
      <!-- 任务信息 -->
      <el-card class="task-info-card">
        <template #header>
          <div class="card-header">
            <span>任务信息</span>
          </div>
        </template>
        <div class="task-info">
          <div class="task-title">
            <h3>{{ task.title }}</h3>
            <div class="task-meta">
              <el-tag :type="getStatusType(task.status) as any" size="small">
                {{ task.status }}
              </el-tag>
              <el-tag :type="getPriorityType(task.priority) as any" size="small" effect="plain">
                {{ getPriorityText(task.priority) }}
              </el-tag>
            </div>
          </div>
          <div class="task-description" v-if="task.description">
            <p>{{ task.description }}</p>
          </div>
          <div class="task-details">
            <div class="detail-item">
              <span class="label">所属项目：</span>
              <span class="value">{{ task.project?.name || '未分配' }}</span>
            </div>
            <div class="detail-item">
              <span class="label">创建时间：</span>
              <span class="value">{{ formatDate(task.createdAt) }}</span>
            </div>
            <div class="detail-item">
              <span class="label">截止时间：</span>
              <span class="value">{{ task.dueDate ? formatDate(task.dueDate) : '未设置' }}</span>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 分配表单 -->
      <el-card class="assign-form-card">
        <template #header>
          <div class="card-header">
            <span>分配设置</span>
          </div>
        </template>
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="120px"
          class="assign-form"
        >
          <el-form-item label="指派给" prop="assigneeId" required>
            <el-select
              v-model="form.assigneeId"
              placeholder="选择负责人"
              style="width: 100%"
              filterable
            >
              <el-option
                v-for="user in users"
                :key="user.id"
                :label="user.username"
                :value="user.id"
              >
                <div class="user-option">
                  <el-avatar :size="24">
                    {{ user.username.charAt(0).toUpperCase() }}
                  </el-avatar>
                  <span class="user-name">{{ user.username }}</span>
                  <span class="user-role">{{ user.role }}</span>
                </div>
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="优先级" prop="priority">
            <el-select v-model="form.priority" placeholder="选择优先级" style="width: 200px">
              <el-option label="低" value="low" />
              <el-option label="中" value="medium" />
              <el-option label="高" value="high" />
              <el-option label="紧急" value="urgent" />
            </el-select>
          </el-form-item>

          <el-form-item label="截止时间" prop="dueDate">
            <el-date-picker
              v-model="form.dueDate"
              type="datetime"
              placeholder="选择截止时间"
              format="YYYY-MM-DD HH:mm"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 300px"
            />
          </el-form-item>

          <el-form-item label="分配说明" prop="note">
            <el-input
              v-model="form.note"
              type="textarea"
              :rows="4"
              placeholder="请输入分配说明或特殊要求..."
              maxlength="500"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="通知设置">
            <el-checkbox v-model="form.notifyAssignee">
              通知被分配人
            </el-checkbox>
            <el-checkbox v-model="form.notifyTeam">
              通知团队成员
            </el-checkbox>
          </el-form-item>

          <el-form-item label="状态更改">
            <el-checkbox v-model="form.changeStatus">
              将任务状态更改为"进行中"
            </el-checkbox>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button @click="goBack">取消</el-button>
      <el-button type="primary" @click="handleAssign" :loading="submitting">
        确认分配
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'

const route = useRoute()
const router = useRouter()
const formRef = ref<FormInstance>()
const submitting = ref(false)

const taskId = ref(Number(route.params.id))

// 任务信息
const task = ref({
  id: 1,
  title: '实现用户认证功能',
  description: '开发用户登录、注册、密码重置等认证相关功能，包括前端界面和后端API。',
  status: '待开始',
  priority: 'high',
  project: { id: 1, name: '项目管理系统' },
  createdAt: new Date('2024-01-15'),
  dueDate: new Date('2024-02-15'),
  assignee: null
})

// 用户列表
const users = ref([
  { id: 1, username: '张三', role: '开发工程师', email: 'zhangsan@example.com' },
  { id: 2, username: '李四', role: '前端工程师', email: 'lisi@example.com' },
  { id: 3, username: '王五', role: '后端工程师', email: 'wangwu@example.com' },
  { id: 4, username: '赵六', role: '测试工程师', email: 'zhaoliu@example.com' },
  { id: 5, username: '钱七', role: '产品经理', email: 'qianqi@example.com' }
])

// 表单数据
const form = reactive({
  assigneeId: null as number | null,
  priority: task.value.priority,
  dueDate: task.value.dueDate ? new Date(task.value.dueDate).toISOString().slice(0, 19).replace('T', ' ') : '',
  note: '',
  notifyAssignee: true,
  notifyTeam: false,
  changeStatus: true
})

// 表单验证规则
const rules: FormRules = {
  assigneeId: [
    { required: true, message: '请选择负责人', trigger: 'change' }
  ]
}

// 获取状态类型
const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    '待开始': 'info',
    '进行中': 'warning',
    '已完成': 'success',
    '已暂停': 'danger'
  }
  return statusMap[status] || ''
}

// 获取优先级类型
const getPriorityType = (priority: string) => {
  const priorityMap: Record<string, string> = {
    low: 'info',
    medium: '',
    high: 'warning',
    urgent: 'danger'
  }
  return priorityMap[priority] || ''
}

// 获取优先级文本
const getPriorityText = (priority: string) => {
  const priorityMap: Record<string, string> = {
    low: '低',
    medium: '中',
    high: '高',
    urgent: '紧急'
  }
  return priorityMap[priority] || priority
}

// 格式化日期
const formatDate = (date: Date | string) => {
  const d = new Date(date)
  return d.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 处理分配
const handleAssign = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    await ElMessageBox.confirm(
      '确定要分配这个任务吗？',
      '确认分配',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    submitting.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 这里应该调用真实的API
    // const result = await taskApi.assignTask(taskId.value, form)
    
    ElMessage.success('任务分配成功')
    router.push(`/tasks/${taskId.value}`)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('分配任务失败:', error)
      ElMessage.error('分配任务失败')
    }
  } finally {
    submitting.value = false
  }
}

// 加载任务数据
const loadTask = async () => {
  try {
    // 这里应该调用API加载任务数据
    // const result = await taskApi.getTask(taskId.value)
    // task.value = result.data
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 300))
  } catch (error) {
    console.error('加载任务数据失败:', error)
    ElMessage.error('加载任务数据失败')
  }
}

// 加载用户列表
const loadUsers = async () => {
  try {
    // 这里应该调用API加载用户列表
    // const result = await userApi.getUsers()
    // users.value = result.data
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 200))
  } catch (error) {
    console.error('加载用户列表失败:', error)
    ElMessage.error('加载用户列表失败')
  }
}

onMounted(() => {
  loadTask()
  loadUsers()
})
</script>

<style scoped>
.assign-task {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 24px;
}

.header-left {
  display: flex;
  align-items: flex-start;
  gap: 16px;
}

.back-btn {
  padding: 8px;
  margin-top: 4px;
}

.header-content h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #333;
}

.header-content p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.content-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
  margin-bottom: 24px;
}

.task-info-card,
.assign-form-card {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.card-header {
  font-weight: 600;
  color: #333;
}

.task-info {
  padding: 0;
}

.task-title {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.task-title h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
  flex: 1;
}

.task-meta {
  display: flex;
  gap: 8px;
  margin-left: 16px;
}

.task-description {
  margin-bottom: 16px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
}

.task-description p {
  margin: 0;
  color: #666;
  line-height: 1.6;
}

.task-details {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 12px;
}

.detail-item {
  display: flex;
  align-items: center;
}

.detail-item .label {
  font-weight: 500;
  color: #666;
  margin-right: 8px;
}

.detail-item .value {
  color: #333;
}

.assign-form {
  max-width: none;
}

.user-option {
  display: flex;
  align-items: center;
  gap: 8px;
  width: 100%;
}

.user-name {
  flex: 1;
  font-weight: 500;
}

.user-role {
  font-size: 12px;
  color: #999;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 16px;
  padding: 20px 0;
  border-top: 1px solid #ebeef5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .assign-task {
    padding: 16px;
  }
  
  .header-left {
    flex-direction: column;
    gap: 8px;
  }
  
  .task-title {
    flex-direction: column;
    gap: 12px;
  }
  
  .task-meta {
    margin-left: 0;
  }
  
  .task-details {
    grid-template-columns: 1fr;
  }
  
  .action-buttons {
    flex-direction: column;
  }
}
</style>